const Joi = require("joi");
const crypto = require("crypto");
const moment = require("moment");
const cryptoUtil = require("../utils/crypto");
module.exports = class ShareController extends colpu.Controller {
  /**
   * @api {get} share/list
   * @apiVersion 1.0.0
   *
   * @apiSuccess {Number} status 状态码
   * @apiSuccess {String} message 消息
   * @apiSuccess {Object} data 返回结果
   * @apiSuccessExample {json} Success-Response:
   * HTTP/1.1 200 OK
      {
        "data": {
          ...
        },
        "status": 0,
        "message": "ok"
      }
  */
  async list(ctx) {
    const res = await this.service.share.list();
    ctx.respond(res);
  }

  async exchangeCode(ctx) {
    await ctx.validateAsync({
      body: {
        exchange_uid: Joi.string().required(),
        code: Joi.string().required(),
      },
      status: 10001,
    });
    try {
      let { data, status } = await this.service.share.exchangeCode(
        ctx.request.body
      );
      ctx.respond(
        data,
        status,
        status == -1
          ? "不存在的兑换码"
          : [
              "兑换换成功",
              "抱歉，自己不能使用自己送出的兑换码～",
              "抱歉，兑换码已使用，换一个试试～",
            ][status]
      );
    } catch (error) {
      ctx.throw(-1, "兑换换失败");
    }
  }
  async exchangeCodePage(ctx) {
    await ctx.validateAsync({
      params: {
        id: Joi.string().required(),
      },
      status: 10001,
    });
    let result;
    try {
      result = await this.service.share.exchangeCodePage(ctx.params);
    } catch {
      ctx.throw(500, "服务器失败了1");
    }
    if (result) {
      ctx.respond(result);
    } else {
      ctx.respond(result, 1, "没相关数据");
    }
  }

  async createCode(ctx) {
    await ctx.validateAsync({
      body: {
        uid: Joi.string().required(),
        pro_id: Joi.number().required(),
      },
      status: 10001,
    });
    const { uid, pro_id } = ctx.request.body;
    const create_time = moment().utc(true).format("YYYY-MM-DD hh:mm:ss");
    const code = moment().utc(true).valueOf();
    try {
      const id = await this.service.share.createCode({
        code,
        create_time,
        uid,
        pro_id,
      });
      ctx.respond({ code, uid, pro_id, id }, 0, "兑换码创建成功");
    } catch (error) {
      ctx.throw(-1, "兑换换失败");
    }
  }
};
